package com.zheng.log;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

//@EnableAutoConfiguration注解实现，通过@import注解导入的类扫描文件，文件内定义了自动配置类，根据文件类加载配置
@Configuration
// 启用对带注释的 bean 的支
@EnableConfigurationProperties(LogProperties.class)
// 仅在Web应用中生效
@ConditionalOnWebApplication
// 读取配置文件来决定是否启用该starter
@ConditionalOnProperty(prefix = "king.log", name = "enabled", havingValue = "true", matchIfMissing = true)
public class LogAutoConfiguration implements WebMvcConfigurer {

    private final LogProperties logProperties;

    public LogAutoConfiguration(LogProperties logProperties) {
        this.logProperties = logProperties;
    }

    @Bean
    @ConditionalOnMissingBean
    public LogInterceptor logInterceptor() {
        return new LogInterceptor(logProperties);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(logInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(logProperties.getIgnorePaths());
    }
}
